import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import {
  getCollectDishAPI,
  addCollectDishAPI,
  deleteCollectDishAPI
} from '@/api/collect'

const STORAGE_KEY = 'collect_store_data'

export const useCollectStore = defineStore(
  'collectStore',
  () => {
    const storedData = uni.getStorageSync(STORAGE_KEY) || {}
    
    const collectDishList = ref(storedData.collectDishList || [])
    const selectedIds = ref(storedData.selectedIds || [])

    watch([collectDishList, selectedIds], () => {
      const dataToStore = {
        collectDishList: collectDishList.value,
        selectedIds: selectedIds.value
      }
      uni.setStorageSync(STORAGE_KEY, dataToStore)
    }, { deep: true })

    // 更新收藏列表 - 确保响应式更新
    const updateCollectDishList = async () => {
      try {
        const res = await getCollectDishAPI()
        if (res && res.code === 1) {
          const dishList = res.data?.collectDishList || []
          collectDishList.value = Array.isArray(dishList) ? [...dishList] : []
          return true
        }
        console.warn('更新收藏列表失败: 接口返回状态异常', res)
        return false
      } catch (error) {
        console.error('更新收藏列表失败:', error)
        return false
      }
    }

    // 删除收藏操作 - 修复选择状态清除逻辑
    const deleteCollectDish = async (ids) => {
      try {
        const idsToDelete = Array.isArray(ids) ? ids : [ids]
        const res = await deleteCollectDishAPI(idsToDelete)
        
        if (res.code === 1) {
          // 1. 先清除选择状态（关键修复：确保无论后续操作如何，先清空选择）
          selectedIds.value = []
          
          // 2. 更新列表
          const updateSuccess = await updateCollectDishList()
          return updateSuccess
        }
        return false
      } catch (error) {
        console.error('删除收藏失败:', error)
        selectedIds.value = []
        return false
      }
    }

    // 全选操作 - 修复全选逻辑
    const toggleSelectAll = () => {
      // 关键修复：全选时基于当前实际列表重新生成ID数组
      if (isAllSelected.value) {
        selectedIds.value = []
      } else {
        // 确保只选择当前存在的菜品ID
        selectedIds.value = collectDishList.value.map(dish => dish.id)
      }
    }

    const addCollectDish = async (id) => {
      try {
        const res = await addCollectDishAPI(id)
        if (res.code === 1) {
          return await updateCollectDishList()
        }
        return false
      } catch (error) {
        console.error('添加收藏失败:', error)
        return false
      }
    }

    const isCollected = (id) => {
      return collectDishList.value.some(dish => dish.id === id)
    }

    const toggleSelect = (id) => {
      if (selectedIds.value.includes(id)) {
        selectedIds.value = selectedIds.value.filter(sid => sid !== id)
      } else {
        selectedIds.value.push(id)
      }
    }

    const isAllSelected = computed(() => {
      return collectDishList.value.length > 0 && 
            selectedIds.value.length === collectDishList.value.length
    })

    const clearSelection = () => {
      selectedIds.value = []
    }

    const selectedCount = computed(() => {
      return selectedIds.value.length
    })

    const clearStorage = () => {
      uni.removeStorageSync(STORAGE_KEY)
      collectDishList.value = []
      selectedIds.value = []
    }

    return {
      collectDishList,
      selectedIds,
      updateCollectDishList,
      addCollectDish,
      deleteCollectDish,
      isCollected,
      toggleSelect,
      isAllSelected,
      toggleSelectAll,
      clearSelection,
      selectedCount,
      clearStorage
    }
  }
)
    